//
//  XBookkeepingViewController.m
//  iAccountBook
//
//  Created by 侯伟 on 2021/8/29.
//

#import "XBookkeepingViewController.h"
#import "XBookkeepingTableViewCell.h"
#import "XBookkeepingSectionHeaderView.h"
#import "RSSwapButton.h"

#import "XBookkeepingItemView.h"
#import <Realm/Realm.h>
#import <LYEmptyView/LYEmptyView.h>
#import <LYEmptyView/UIView+Empty.h>

#import "RSDatePickerViewController.h"
#import "XBookkeepingEditViewController.h"

#import "XDynamicModel.h"
#import "XBudgetModel.h"
#import "RFaceCheckRequest.h"

@interface XBookkeepingViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)MyRelativeLayout *rootLayout;


@property(nonatomic,strong)MyLinearLayout *contentLayout;

/// 剩余title
@property(nonatomic,strong)UILabel* reduceTitleLb;

/// 剩余金额
@property(nonatomic,strong)UILabel* reduceAmtLb;

/// 预算设置
@property(nonatomic,strong)UIButton* budgetBtn;

/// 支出
@property(nonatomic,strong)UILabel* incomeAmtLb;

/// 支出
@property(nonatomic,strong)UILabel* expendAmtLb;

/// 明细
@property(nonatomic,strong)UITableView* tableView;

/// 明细数据
@property(nonatomic,strong)NSArray* datas;

/// 明细数据
@property(nonatomic,strong)XBudgetModel* budget;

/// 当前时间
@property(nonatomic,strong)NSDate* currentDate;

@end

@implementation XBookkeepingViewController

- (void)loadView{
    [super loadView];
   
    self.view.backgroundColor = COLOR_BACKGEOUND;
    
    // 根视图
    MyRelativeLayout *rootLayout = [MyRelativeLayout new];
    rootLayout.myMargin = 0;
    [self.view addSubview:rootLayout];
    _rootLayout = rootLayout;

    // 线性布局
    MyLinearLayout *contentLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    contentLayout.myMargin = 0;
    [rootLayout addSubview:contentLayout];
    _contentLayout = contentLayout;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    [self setupViews];
}


-(void)setupViews{
    
    //新增按钮
    UIButton* addBtn = [UIButton new];
    [addBtn setImage:[UIImage imageNamed:@"x_dynamic_add"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addBookkeeping:) forControlEvents:UIControlEventTouchUpInside];
    addBtn.myBottom = 8;
    addBtn.myRight = 0;
    [addBtn sizeToFit];
    [self.rootLayout addSubview:addBtn];
    
    
    MyLinearLayout* topLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    topLayout.backgroundColor = UIColor.whiteColor;
    topLayout.myHorzMargin = 16;
    topLayout.myTop = 10;
    topLayout.myHeight = MyLayoutSize.wrap;
    topLayout.padding = UIEdgeInsetsMake(20, 20, 20, 20);
    topLayout.layer.cornerRadius = PX(8);
    [self.contentLayout addSubview:topLayout];
    
    //预算剩余title
    UILabel* reduceTitleLb = [UILabel lableWithFont:FONT_FIT(14) color:COLOR_GRAY_BASE text:@""];
    reduceTitleLb.myHorzMargin = 0;
    [topLayout addSubview:reduceTitleLb];
    _reduceTitleLb = reduceTitleLb;
    
    //预算剩余金额
    UILabel* reduceAmtLb = [UILabel lableWithFont:NUMBERFONT_FIT(20) color:COLOR_BLACK_DARK text:@"￥0"];
    reduceAmtLb.myTop = 16;
    reduceAmtLb.myHorzMargin = 0;
    [topLayout addSubview:reduceAmtLb];
    _reduceAmtLb = reduceAmtLb;
    
    
    MyLinearLayout *subLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
    subLayout.myHeight = MyLayoutSize.wrap;
    subLayout.myTop = 16;
    subLayout.myHorzMargin = 0;
    subLayout.subviewHSpace = 20;
    [topLayout addSubview:subLayout];
    
    //预算
    UIButton* budgetBtn = [[UIButton alloc] init];
    [budgetBtn setTitleColor:COLOR_GRAY_BASE forState:UIControlStateNormal];
    [budgetBtn setTitle:@"预算设置" forState:UIControlStateNormal];
    [budgetBtn addTarget:self action:@selector(setBudget:) forControlEvents:UIControlEventTouchUpInside];
    budgetBtn.titleLabel.font = NUMBERFONT_FIT(13);
    budgetBtn.layer.cornerRadius = PX(40);
    budgetBtn.layer.borderColor = COLOR_ORANGE.CGColor;
    budgetBtn.layer.borderWidth = 5.0;
    budgetBtn.mySize = CGSizeMake(PX(80), PX(80));
    budgetBtn.myMargin = 0;
    [subLayout addSubview:budgetBtn];
    _budgetBtn = budgetBtn;
    
    //支出/收入汇总
    MyLinearLayout *detailsLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    detailsLayout.myHeight = MyLayoutSize.wrap;
    detailsLayout.myCenterY = 0;
    detailsLayout.weight = 1.0;
    detailsLayout.subviewVSpace = 32;
    detailsLayout.gravity = MyGravity_Vert_Center;
    [subLayout addSubview:detailsLayout];
    
    //收入
    MyLinearLayout *incomeLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
    incomeLayout.myHeight = MyLayoutSize.wrap;
    incomeLayout.myMargin = 0;
    incomeLayout.gravity = MyGravity_Horz_Between;
    [detailsLayout addSubview:incomeLayout];
    
    UILabel* incomeTitleLb = [UILabel lableWithFont:FONT_FIT(14) color:COLOR_GRAY_BASE text:@"本月生活收入"];
    incomeTitleLb.myMargin = 0;
    [incomeLayout addSubview:incomeTitleLb];
    
    //收入金额
    UILabel* incomeAmtLb = [UILabel lableWithFont:NUMBERFONT_FIT(20) color:COLOR_GREEN text:@"￥0"];
    incomeAmtLb.myHeight = PX(20);
    incomeAmtLb.myMargin = 0;
    [incomeLayout addSubview:incomeAmtLb];
    _incomeAmtLb = incomeAmtLb;
    
    
    MyLinearLayout *expendLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
    expendLayout.myHeight = MyLayoutSize.wrap;
    expendLayout.myMargin = 0;
    expendLayout.gravity = MyGravity_Horz_Between;
    [detailsLayout addSubview:expendLayout];
    
    UILabel* expendTitleLb = [UILabel lableWithFont:FONT_FIT(14) color:COLOR_GRAY_BASE text:@"本月生活支出"];
    expendTitleLb.myMargin = 0;
    [expendLayout addSubview:expendTitleLb];
    
    //支出金额
    UILabel* expendAmtLb = [UILabel lableWithFont:NUMBERFONT_FIT(20) color:COLOR_RED text:@"￥0"];
    expendAmtLb.myHeight = PX(20);
    expendAmtLb.myMargin = 0;
    [expendLayout addSubview:expendAmtLb];
    _expendAmtLb = expendAmtLb;
    
    UIView* line = [UIView new];
    line.myTop = 16;
    line.myHorzMargin = 0;
    line.myHeight = Size_1PX;
    line.backgroundColor = COLOR_GRAY_LINE;
    [topLayout addSubview:line];
    
    
    RSSwapButton* flodBtn = [[RSSwapButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-32, PX(40))];
    flodBtn.gap = 8;
    [flodBtn setTitle:@"明细" forState:UIControlStateNormal];
    [flodBtn setTitle:@"收起" forState:UIControlStateNormal];
    [flodBtn setTitleColor:COLOR_GRAY_BASE forState:UIControlStateNormal];
    [flodBtn setImage:[UIImage imageNamed:@"x_bookkeeping_fold"] forState:UIControlStateNormal];
    [flodBtn addTarget:self action:@selector(flodList:) forControlEvents:UIControlEventTouchUpInside];
    flodBtn.titleLabel.font = FONT_FIT(12);
    flodBtn.myRight = 0;
    flodBtn.myTop = 14;
    flodBtn.myWidth = PX(40);
    flodBtn.myHeight = PX(20);
    [topLayout addSubview:flodBtn];
     
    
    //列表
    UITableView* tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.backgroundColor = COLOR_BACKGEOUND;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.rowHeight = PX(50);
    tableView.sectionHeaderHeight = PX(44);
    tableView.tableFooterView = [UIView new];
    [tableView registerClass:NSClassFromString(bookkeepingCell) forCellReuseIdentifier:bookkeepingCell];
    [tableView registerClass:NSClassFromString(bookkeepingHeader) forHeaderFooterViewReuseIdentifier:bookkeepingHeader];
    tableView.layer.cornerRadius = PX(8);
    tableView.layer.masksToBounds = YES;
    tableView.myHorzMargin = 16;
    tableView.weight = 1.0;
    [self.contentLayout addSubview:tableView];
    _tableView = tableView;
    
    LYEmptyView* emptyView = [LYEmptyView emptyViewWithImageStr:NULL titleStr:@"您还没有记录哟" detailStr:@"快来记录每一天的生活吧"];
    emptyView.titleLabFont = FONT_FIT(12);
    emptyView.titleLabTextColor = COLOR_BLACK_DARK;
    emptyView.detailLabFont = FONT_FIT(12);
    emptyView.detailLabTextColor = COLOR_GRAY_BASE;
    emptyView.detailLabMargin = 10;
    emptyView.contentViewOffset = -10;
    tableView.ly_emptyView = emptyView;
    
}

- (void)updateViews{
    
    self.reduceTitleLb.text = [NSString stringWithFormat:@"%@生活预算余额",[_currentDate stringWithFormat:@"yyyy年MM月"]];
    [self.reduceTitleLb sizeToFit];
    

    if(_budget){
        [self.budgetBtn setTitle:[NSString stringWithFormat:@"￥%.2f",_budget.feeAmt] forState:UIControlStateNormal];
    }else{
        [self.budgetBtn setTitle:@"预算设置" forState:UIControlStateNormal];
    }
    [self.budgetBtn sizeToFit];
    
    CGFloat income = 0.0;
    CGFloat ecpend = 0.0;
    for (NSArray* arr in self.datas) {
        if(arr.count){
            XDynamicModel* model = arr.firstObject;
            if([[model.date stringYearMonth] isEqualToString:[_currentDate stringYearMonth]]){
                for (XDynamicModel* obj in arr) {
                    if(obj.feeType > 200){
                        ecpend += obj.feeAmt;
                    }else{
                        income += obj.feeAmt;
                    }
                }
                break;
            }
        }
    }
    self.incomeAmtLb.text = [NSString stringWithFormat:@"￥%.2f",income];
    [self.incomeAmtLb sizeToFit];
    self.expendAmtLb.text = [NSString stringWithFormat:@"￥%.2f",ecpend];
    [self.expendAmtLb sizeToFit];
    
    CGFloat amt = income - ecpend;
    if(_budget){
        amt = _budget.feeAmt + income - ecpend;
    }
    self.reduceAmtLb.text = [NSString stringWithFormat:@"￥%.2f",amt];
    [self.reduceAmtLb sizeToFit];
}


#pragma mark -- reloadData
// 刷新数据
- (void)reloadData{
    
    _currentDate = [NSDate date];
    
    RLMResults* budgets = [XBudgetModel objectsWhere:@"month = %@",[_currentDate stringYearMonth]];
    if(budgets.count){
        _budget = budgets.firstObject;
    }else{
        _budget = NULL;
    }
    
    RLMResults* incomeDatas = [[XDynamicModel objectsWhere:@"type = 2"] sortedResultsUsingKeyPath:@"date" ascending:NO];
    
    self.datas = [self category:incomeDatas];
    
    [self updateViews];
    
    [self.tableView reloadData];
}

-(NSArray*)category:(RLMResults*)datas{
    
    if(!datas.count) return @[];
    
    //分好组的数组
    NSMutableArray* groupArray = [NSMutableArray array];
    
    //遍历时，时间相同的装在同一个数组中，先取_dataArray[0]分一组
    NSMutableArray *currentArr = [NSMutableArray array];

    [currentArr addObject:datas.firstObject];

    [groupArray addObject:currentArr];
    
    if(datas.count > 1){

        for (int i = 1 ;i < datas.count ; i++){
            
            //取上一组元素并获取上一组元素的比较日期
            NSArray *preArr = groupArray.lastObject;
            
            XDynamicModel *firstObj = preArr.firstObject;
            NSString *preStr = [firstObj.date stringYearMonth];
            
            //取当前遍历的字典中的日期
            XDynamicModel *currentObj = [datas objectAtIndex:i];
            NSString *timeStr = [currentObj.date stringYearMonth];
            
            //如果遍历当前字典的日期和上一组元素中日期相同则把当前字典分类到上一组元素中
            if([timeStr isEqualToString:preStr]){
                [currentArr addObject:currentObj];
            }
    //如果当前字典的日期和上一组元素日期不同，则重新开新的一组，把这组放入到分类数组中
            else{
                currentArr = [NSMutableArray array];
                [currentArr addObject:currentObj];
                [groupArray addObject:currentArr];
            }
        }
    }
    return groupArray;
}

#pragma mark -- action

- (void)setBudget:(UIButton*)sender{
    RSDatePickerViewController* datePicker = [RSDatePickerViewController new];
    datePicker.dateStyle = DateStyleShowYearMonth;
    datePicker.currentDate = _currentDate;
    datePicker.titleStr = @"选择月份";
    [datePicker presentOverViewController:self.tabBarController];
    datePicker.doneBlock = ^(NSDate * _Nonnull date) {
        NSString* title = [NSString stringWithFormat:@"设置%@生活预算",[date stringWithFormat:@"yyyy年MM月"]];
        [Alert systemPrompt:title text:NULL placeholder:@"请输入本月生活预算金额" completion:^(NSString * _Nullable string) {
            XBudgetModel* budget = [XBudgetModel new];
            budget.month = [date stringYearMonth];
            budget.feeAmt = [string floatValue];
            
            [[RLMRealm defaultRealm] transactionWithBlock:^{
                [[RLMRealm defaultRealm] addOrUpdateObject:budget];
            }];
            [self reloadData];
        }];
    };
}

//折叠
- (void)flodList:(UIButton*)sender{
    sender.selected = !sender.selected;
    
    CGAffineTransform transform = sender.selected?CGAffineTransformMakeRotation(-M_PI):CGAffineTransformIdentity;
    [UIView animateWithDuration:0.15 animations:^{
        sender.imageView.transform = transform;
    }];
    
    self.tableView.visibility = sender.selected?MyVisibility_Gone:MyVisibility_Visible;
}

//添加
- (void)addBookkeeping:(UIButton*)sender{
    XBookkeepingEditViewController* editController = [XBookkeepingEditViewController new];
    [UIViewController showViewController:editController animated:YES];
}

#pragma mark --UITableViewDelegate  UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray* arr = self.datas[section];
    return arr.count;
}


- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    NSArray* arr = self.datas[section];
    XDynamicModel* model = arr.firstObject;
    
    XBookkeepingSectionHeaderView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:bookkeepingHeader];
    headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, PX(44));
    
    headerView.timeLb.text = [model.date stringWithFormat:@"yyyy年MM月"];
    [headerView.timeLb sizeToFit];
    
    CGFloat income = 0.0;
    CGFloat ecpend = 0.0;
    for (XDynamicModel* obj in arr) {
        if(obj.feeType > 200){
            ecpend += obj.feeAmt;
        }else{
            income += obj.feeAmt;
        }
    }
    CGFloat amt = income - ecpend;
    headerView.amtLb.text = [NSString stringWithFormat:@"%@￥%.2f",amt>=0?@"+":@"-",fabs(amt)];
    headerView.amtLb.textColor = amt>0?COLOR_GREEN:COLOR_RED;
    [headerView.amtLb sizeToFit];
    
    
    return headerView;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    NSArray* arr = self.datas[indexPath.section];
    XDynamicModel* model = arr[indexPath.row];
    
    XBookkeepingTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:bookkeepingCell forIndexPath:indexPath];
    cell.model = model;
    return cell;
   
    return [UITableViewCell new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -- check

-(void)requestData{
    //getEtc 3-a 4-b
    RFaceCheckRequest* request = [RFaceCheckRequest new];
    [RequestOperation request:request quite:YES callBack:^(HResponse * _Nullable response) {
        [response success:^(id  _Nonnull data) {
            NSArray* list = [NSArray yy_modelArrayWithClass:XDynamicModel.class json:data];
            if(list.count == 4){
                [[NSNotificationCenter defaultCenter] postNotificationName:kChangeNotification object:NULL userInfo:NULL];
            }else{
                [self reloadData];
            }
        }];
    }];
}
@end
